package shop.up.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import shop.up.common.constant.MqConst;
import shop.up.common.service.RabbitService;
import shop.up.model.enums.PaymentStatus;
import shop.up.model.order.OrderInfo;
import shop.up.model.payment.PaymentInfo;
import shop.up.payment.mapper.PaymentInfoMapper;
import shop.up.payment.service.PaymentService;

import java.util.Date;
import java.util.Map;

/**
 * TODO {@link PaymentServiceImpl}
 *
 * @author Kevin
 * @date 2022/7/28
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Autowired
    private RabbitService rabbitService;

    /**
     * 保存交易记录
     * @param orderInfo
     * @param paymentType 支付类型（1：微信 2：支付宝）
     */
    @Override
    public void savePaymentInfo(OrderInfo orderInfo, String paymentType) {
        // 幂等性
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderInfo.getId());
        queryWrapper.eq("payment_type", paymentType);
        Integer count = paymentInfoMapper.selectCount(queryWrapper);
        if(count > 0) {
            return;
        }

        // 保存交易记录
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
        paymentInfo.setSubject(orderInfo.getTradeBody());
        paymentInfo.setTotalAmount(orderInfo.getTotalAmount());

        paymentInfoMapper.insert(paymentInfo);
    }

    /**
     * 获取交易记录信息
     * @param outTradeNo
     * @param name
     * @return
     */
    @Override
    public PaymentInfo getPaymentInfo(String outTradeNo, String name) {
        //  select * from payment_info where out_trade_no = ? and payment_type = ?
        QueryWrapper<PaymentInfo> paymentInfoQueryWrapper = new QueryWrapper<>();
        paymentInfoQueryWrapper.eq("out_trade_no",outTradeNo);
        paymentInfoQueryWrapper.eq("payment_type",name);
        return paymentInfoMapper.selectOne(paymentInfoQueryWrapper);
    }

    /**
     * 支付成功后处理
     * @param outTradeNo
     * @param name
     * @param paramMap
     */
    @Override
    public void paySuccess(String outTradeNo, String name, Map<String, String> paramMap) {
        // 交易状态如果是 CLOSE 或 PAID, 则直接返回, 不需要处理
        PaymentInfo paymentInfoQuery = getPaymentInfo(outTradeNo, name);
        if (paymentInfoQuery.getPaymentStatus().equals(PaymentStatus.PAID.name()) ||
                paymentInfoQuery.getPaymentStatus().equals(PaymentStatus.ClOSED.name())){
            return;
        }

        // 更新交易状态
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setTradeNo(paramMap.get("trade_no"));
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
        paymentInfo.setCallbackContent(paramMap.toString());

        updatePaymentInfo(outTradeNo, name, paymentInfo);

        // 发送消息，更改订单状态
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,
                MqConst.ROUTING_PAYMENT_PAY, paymentInfoQuery.getOrderId());

    }

    @Override
    public void updatePaymentInfo(String outTradeNo, String name, PaymentInfo paymentInfo) {
        QueryWrapper<PaymentInfo> paymentInfoQueryWrapper = new QueryWrapper<>();
        paymentInfoQueryWrapper.eq("out_trade_no",outTradeNo);
        paymentInfoQueryWrapper.eq("payment_type",name);

        paymentInfoMapper.update(paymentInfo, paymentInfoQueryWrapper);
    }
}
